package edu.washington.vaccine.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import edu.washington.vaccine.R;
import edu.washington.vaccine.backend.Patient;
import edu.washington.vaccine.backend.Vaccine;
import edu.washington.vaccine.backend.VaccineLocalHelper;


/*
 * Populates screen with a list of viable vaccines as determined by the
 * forecasting model from patient data and vaccine schedule data
 */
public class ChooseVaccineActivity extends Activity {
	@SuppressWarnings("unused")
	private static final String TAG = "ChooseVaccineActivity";
	private VaccineLocalHelper localDB;
//	private VaccineDB exDB;
	Patient p;
	Patient oldP;
	String history;
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Activity thisActivity = this;
		setContentView(R.layout.log_vaccine);
		View root = ((ViewGroup) findViewById(android.R.id.content)).getRootView();
        root.setFocusable(true);
        root.setFocusableInTouchMode(true);
        root.requestFocus();
		Bundle data = getIntent().getExtras();
		p = (Patient) data.getSerializable("patient");
		history = (String) data.getSerializable("history");
		oldP = (Patient) data.getSerializable("oldPatient");
//		exDB = VaccineDB.getInstance();
		ScrollView sv = new ScrollView(this);
		//sv.setBackgroundColor(R.color.white);
		Button logVaccineButton = new Button(this);
		logVaccineButton.setText(R.string.give_vaccine);
		logVaccineButton.setLayoutParams(new LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT));

		TableLayout tl = new TableLayout(this);
		sv.addView(tl);
		//local vaccine database
		localDB = VaccineLocalHelper.getInstance(this);
		final List<Vaccine> pArray = new ArrayList<Vaccine>();

		Cursor cursor = localDB.getReadableDatabase().rawQuery("SELECT * FROM Vaccines", new String [] {});
		startManagingCursor(cursor);
		// collect data from local database 
		while (cursor.moveToNext()) {
			int vid = cursor.getInt(0);
			String vname = cursor.getString(1);
//			int vdose = cursor.getInt(2);
			String vdesc = cursor.getString(2);
			String vschedule = cursor.getString(3);
			pArray.add(new Vaccine(vid, vname, vdesc, vschedule));
		}
		cursor.close();
		if (history == null)
			history = PatientDataActivity.getVaccineHistory(this, "" + p.id);
		String[] birthdate = p.dob.split("-");
		
		for(Vaccine v : pArray) {
			String[] schedule = v.schedule.split(";");
			int[] intSchedule = new int[schedule.length];
			for (int i = 0; i < schedule.length; i++)
				intSchedule[i] = Integer.parseInt(schedule[i]);
			
			int administeredSoFar = history.split(v.name).length - 1;
			if (administeredSoFar >= schedule.length)
				continue;
			
			// if birthdate + schedule[administeredSoFar] < current date, show red
			// else if < current date + 1 week, show black
			// else dont show
			Calendar scheduled = Calendar.getInstance();
			scheduled.set(Integer.parseInt(birthdate[2]), Integer.parseInt(birthdate[0]) - 1, Integer.parseInt(birthdate[1]));
			scheduled.add(Calendar.DATE, intSchedule[administeredSoFar] * 7);
			
			Calendar current = Calendar.getInstance();
			current.add(Calendar.DATE, 7);
//			System.out.println("scheduled is " + scheduled.getTime() + " while current is " + current.getTime()
//					+ " and current is after scheduled " + current.after(scheduled));
			if (current.after(scheduled)) {
				TableRow tr = new TableRow(this);
				CheckBox chk = new CheckBox(this);
				chk.setText(v.name);
				chk.setId(v.id);
				chk.setTextColor(Color.BLACK);
				
				current.add(Calendar.DATE, -14);
				if (current.after(scheduled)) {
					chk.setTextColor(Color.YELLOW);
					chk.setBackgroundColor(Color.RED);
				}
				
				tr.addView(chk);
				tl.addView(tr);
			}
		}
		tl.addView(logVaccineButton);
		setContentView(sv);

		logVaccineButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String[] vaccineInfo = new String[pArray.size()*2+1];
				String printInfo = "";
				int count = 1;
				Date d = Calendar.getInstance().getTime();
				String date = "";
				int month = d.getMonth() + 1;
				int day = d.getDate();
				int year = d.getYear() + 1900;

				if (month < 10)
					date = "0";
				date += month + "-";

				if (day < 10)
					date += "0";
				date += day + "-" + year;
//				String date = (d.getMonth() + 1) + "-" + d.getDate() + "-" + (d.getYear() + 1900);
				vaccineInfo[0] = "" + p.id;
				CheckBox c;
				for(Vaccine currentVaccine : pArray) {
					c = ((CheckBox) findViewById(currentVaccine.id));
					if (c != null && c.isChecked()) {
						vaccineInfo[count] = "" + currentVaccine.id;
//						vaccineInfo[count+1] = "" + currentVaccine.dose;
						printInfo += currentVaccine.name + ", " + date + "\n";
						count++;
					}
				}
				
//				Toast.makeText(ChooseVaccineActivity.this, "" + p.id, Toast.LENGTH_SHORT).show();
				
				Intent i = new Intent(thisActivity, PostChooseVaccineActivity.class);
				i.putExtra("newVaccine", vaccineInfo); 
				i.putExtra("patient", p);
				i.putExtra("printInfo", printInfo);
				FirstGroup.group.addChildActivity("savevaccine", i);
//				VaccineActivity parentActivity = (VaccineActivity)thisActivity.getParent();
//				parentActivity.replaceContentView("savevaccine", i);
				
//				Intent i = new Intent(thisActivity, VaccineActivity.class);
//				VaccineActivity parentActivity = (VaccineActivity)thisActivity.getParent();
//				parentActivity.replaceContentView("nextactivity", i);
			}
		});
	}

	public void onCheckboxClicked(View v) {
		// Perform action on clicks, depending on whether it's now checked
		if (((CheckBox) v).isChecked()) {
			Toast.makeText(ChooseVaccineActivity.this, "Selected", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(ChooseVaccineActivity.this, "Not selected", Toast.LENGTH_SHORT).show();
		}
	}


	@Override
	public void onBackPressed() {
		Intent i = new Intent(this, PatientDataActivity.class);
		i.putExtra("patient", p);
		i.putExtra("oldPatient", oldP);
//		VaccineActivity parentActivity = (VaccineActivity)getParent();
//		parentActivity.replaceContentView("patientdata", i);
		FirstGroup.group.back();
	}

}